//
//  FirstViewController.m
//  minfubaoLib
//
//  Created by 钱坚 on 15/11/9.
//  Copyright © 2015年 苏州鱼儿信息科技有限公司. All rights reserved.
//

#import "FirstViewController.h"
#import "UINavigationBar+Awesome.h"
#import "RDVTabBarController.h"
#import "RDVTabBarItem.h"
#import "WebViewController.h"
#import "LoginViewController.h"

#import "BestpaySDK.h"
#import "BestpayNativeModel.h"


#import <Security/Security.h>
#import "MD5.h"

#define KEYSTR @"4D9055BB53FB86FE"
#define MERID @"3205000006"
#define PSWD @"412333"

#import "CommoneTools.h"
#import "UIView+SDExtension.h"
#import "SDHomeGridView.h"
#import "SDHomeGridItemModel.h"
#import "SDGridItemCacheTool.h"
#import "EmptyView.h"

#define kHomeHeaderViewHeight kScreenW*0.6

@interface FirstViewController ()<NSURLConnectionDelegate,SDHomeGridViewDeleate,EmptyReloadDelegate>{
    
    XLCycleScrollView *csView;
    NSMutableArray *banners;
    NSMutableArray *modules;
    
}
@property (nonatomic, strong) NSMutableDictionary *params;
@property (nonatomic,strong) EmptyView *emptyView;
@property (nonatomic, strong) NSMutableData *receiveData;
@property (nonatomic, strong) NSURLConnection *connection;

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) SDHomeGridView *mainView;
@property (nonatomic, strong) NSArray *dataArray;

@end

@implementation FirstViewController
@synthesize tableview;


- (instancetype)initWithInfo:(NSObject *)obj{
    self = [super init];
    if (self) {
        
    }
    return self;
}

-(void)emptyReloadBtnAction{
    [self laodData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.emptyView = [EmptyView getInstance];
    self.emptyView.delegate=self;
    [self setCustomLeftButton:self action:@selector(leftclick) img:@"logo_2x"];
    [self laodData];
}


-(void)laodData{
    
    if ([CommoneTools isConnectionAvailable]) {
        [self.emptyView removeFromSuperview];
    } else {
        [self.emptyView showByView:self.view];
        return;
    }
    
    advListInfoModel *adv = [[advListInfoModel alloc] init];
    banners = [[NSMutableArray alloc] initWithObjects:adv, nil];
    
    JGProgressHUD * hud = [utils getProcess:JGProgressHUDStyleExtraLight interaction:JGProgressHUDInteractionTypeBlockAllTouches zoom:NO dim:NO shadow:YES];
    [utils showSimpleHUD:hud showText:nil target:nil];
    
    [HttpNetWorkUtil requestshortLogin:nil success:^(id json) {
        [hud dismiss];
        [self setupMainView];
        
        InfoDataModel *infodatamodel = [[InfoDataModel alloc] init];
        [infodatamodel fillWithJsonDict:json];
        
        NSData *data = [RFJModel toDataWithModel:infodatamodel];
        [utils setObject:data forkey:PERSONINFO];
        
        if (infodatamodel.infomodel.advList.count>0) {
            banners = [[NSMutableArray alloc] initWithArray:infodatamodel.infomodel.advList];
            [csView reloadData];
        }
        
        modules = [[NSMutableArray alloc] initWithArray:infodatamodel.infomodel.moduleList];
        
        
        
        NSMutableArray *saveTemp = [[NSMutableArray alloc] init];
        for (int i =0; i<modules.count; i++) {
            moduleListInfoModel *model = [modules objectAtIndex:i];
            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
            
            [dict setObject:model.modName?model.modName:@"" forKey:@"title"];
            [dict setObject:model.icon?model.icon:@"" forKey:@"icon"];
            [dict setObject:model.modDesc?model.modDesc:@"" forKey:@"subtitle"];
            [dict setObject:model.modId?model.modId:@"" forKey:@"id"];
            [dict setObject:model.isNew?model.isNew:@"" forKey:@"isnew"];
            [dict setObject:model.isNewActive?model.isNewActive:@"" forKey:@"isNewActive"];
            
            [saveTemp addObject:dict];
        }
        [SDGridItemCacheTool saveItemsArray:saveTemp];
        
        
        [self setupDataArray];
        _mainView.gridModelsArray = _dataArray;
        
    } fail:^{
        [hud dismiss];
    }];
}

-(void)leftclick{
    
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    CGFloat tabbarHeight = [[self.tabBarController tabBar] sd_height];
    
    CGFloat headerY = 0;
    _headerView.frame = CGRectMake(0, headerY, self.view.sd_width, kHomeHeaderViewHeight);
    _mainView.frame = CGRectMake(0, _headerView.sd_y + kHomeHeaderViewHeight, self.view.sd_width, self.view.sd_height - kHomeHeaderViewHeight - tabbarHeight);
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
    
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar lt_setBackgroundColor:[utils getThemeColor]];
    [self.navigationController.navigationBar setShadowImage:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


- (void)setupMainView{
    _headerView = [[UIView alloc] init];
    [_headerView setBackgroundColor:[UIColor grayColor]];
    [self.view addSubview:_headerView];
    
    [self getBanner:CGRectMake(0, 0, kScreenW, kHomeHeaderViewHeight)];
    
    _mainView = [[SDHomeGridView alloc] init];
    _mainView.gridViewDelegate = self;
    _mainView.showsVerticalScrollIndicator = NO;
    
    [self setupDataArray];

    [self.view addSubview:_mainView];
}

- (void)setupDataArray
{
    NSArray *itemsArray = [SDGridItemCacheTool itemsArray];
    NSMutableArray *temp = [NSMutableArray array];
    for (NSDictionary *itemDict in itemsArray) {
        SDHomeGridItemModel *model = [[SDHomeGridItemModel alloc] init];
        //        model.destinationClass = [SDBasicViewContoller class];
        model.imageResString =[itemDict objectForKey:@"icon"];
        model.title = [itemDict objectForKey:@"title"];
        model.subtitle = [itemDict objectForKey:@"subtitle"];
        model.url = [itemDict objectForKey:@"id"];
        model.isnew = [itemDict objectForKey:@"isnew"];
        model.isNewActive = [itemDict objectForKey:@"isNewActive"];
        
        [temp addObject:model];
    }
    _dataArray = [temp copy];
}

#pragma mark - SDHomeGridViewDeleate

- (void)homeGrideView:(SDHomeGridView *)gridView selectItemAtIndex:(NSInteger)index
{
    SDHomeGridItemModel *SDmodel = _dataArray[index];
    moduleListInfoModel *model_touch;
    for (int i=0; i<modules.count; i++) {
        moduleListInfoModel *model = [modules objectAtIndex:i];
        if ([model.modId isEqualToString:SDmodel.url]) {
            model_touch = model;
            break;
        }
        
    }
    
    // 需要登陆
    if ([model_touch.lastUpdateBy isEqualToString:@"0"] && [utils getObject:PERSONINFO] == nil) {
        
        LoginViewController *view = [[LoginViewController alloc] init];
        [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
        [self.navigationController pushViewController:view animated:YES];
        
    }else if (model_touch && model_touch.url && ![model_touch.url isEqualToString:@""]) {
        
        InfoDataModel *person = [utils getPersonInfo];
        NSString *memberId = person.infomodel.m.memberId?person.infomodel.m.memberId:@"";
        NSString *modToken = model_touch.modToken?model_touch.modToken:@"";
        
        [HttpNetWorkUtil requestinsertModule:@{@"memberId":memberId,@"modToken":modToken} success:^(id json) {
        } fail:^{}];
        
        if ([(AppDelegate *)[UIApplication sharedApplication].delegate isConnectionAvailable]) {
            WebViewController *view = [[WebViewController alloc] initWithUrl:model_touch.url withTitle:nil];
            [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
            [self.navigationController pushViewController:view animated:YES];
        }
    }
}

- (void)homeGrideViewmoreItemButtonClicked:(SDHomeGridView *)gridView
{

}

- (void)homeGrideViewDidChangeItems:(SDHomeGridView *)gridView
{
    [self setupDataArray];
}


-(BOOL)textFieldShouldBeginEditing:(UITextField*)textField//实现这个代理
{
    //    if (textField == self.searchBar) {
    //        //        [self.tableview.header beginRefreshing];
    //        [textField resignFirstResponder];
    //        SearcherViewController *view = [[SearcherViewController alloc]init];
    //        [self.navigationController pushViewController:view animated:YES];
    //        return NO;
    //    }
    return YES;
}

-(void)getBanner:(CGRect)rect{
    
    csView = [[XLCycleScrollView alloc] initWithFrame:rect];
    csView.delegate = self;
    csView.datasource = self;
    [_headerView addSubview:csView];
    //    [self.myScrollView addSubview:csView];
}

- (NSInteger)numberOfPages
{
    return banners.count;
}

- (UIView *)pageAtIndex:(NSInteger)index
{
    advListInfoModel *adv = [banners objectAtIndex:index];
    
    NSString *img_url=adv.imgPath;
    
    UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, csView.frame.size.width, csView.frame.size.height)];
    //    [imageview setContentMode:UIViewContentModeScaleAspectFill];//防止变形
    UIImage *defualt_img;
    if (imageview.frame.size.height != imageview.frame.size.width) {
        defualt_img = [utils addImage:[UIImage imageNamed:@"default"] withsize:imageview.frame.size];
    }else{
        defualt_img = [UIImage imageNamed:@"default"];
    }
    
    //    [imageview setImage:[UIImage imageNamed:@"xiaoxitupian"]];
    [imageview sd_setImageWithURL:[NSURL URLWithString:img_url] placeholderImage:nil options:SDWebImageRefreshCached|SDWebImageContinueInBackground|SDWebImageRetryFailed];
    
    return imageview;
}

- (void)didClickPage:(XLCycleScrollView *)csView atIndex:(NSInteger)index
{
    advListInfoModel *adv = [banners objectAtIndex:index];
    NSString *url=adv.linkUrl;
    if (url && ![url isEqualToString:@""]) {
        if ([(AppDelegate *)[UIApplication sharedApplication].delegate isConnectionAvailable]) {
            WebViewController *view = [[WebViewController alloc]initWithUrl:url withTitle:@""];
            [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
            
            [self.navigationController pushViewController:view animated:YES];
        }
    }
}

//测试翼支付
-(void)initTestBestPayBtn{
    UIButton *testBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    testBtn.frame = CGRectMake(self.view.frame.size.width/2-100, self.view.frame.size.height/2-25, 200, 50);
    [testBtn setBackgroundColor:[UIColor redColor]];
    [testBtn setTitle:@"翼支付" forState:UIControlStateNormal];
    [testBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [testBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];
    [self.view addSubview:testBtn];
    [testBtn addTarget:self action:@selector(pay:) forControlEvents:UIControlEventTouchUpInside];
}

#define releaseURL @"https://webpaywg.bestpay.com.cn/order.action"


-(IBAction)pay:(id)sender{
    NSString *orderSeq = [self getOrderTimeMS];
    NSString *orderReqTrnSeq = [NSString stringWithFormat:@"%@0001",orderSeq];
    NSString *orderTime = [self getOrderTime];
    NSString *amount = @"0.01";
    
    self.receiveData = [[NSMutableData alloc] init];
    NSURL *url = [NSURL URLWithString:releaseURL];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    NSString* signOrigStr = [NSString stringWithFormat:@"MERCHANTID=%@&ORDERSEQ=%@&ORDERREQTRANSEQ=%@&ORDERREQTIME=%@&KEY=%@", MERID,orderSeq,orderReqTrnSeq,orderTime, KEYSTR];
    NSLog(@"下单签名源串 singOrigStr = %@", signOrigStr);
    NSString *signMac = [MD5 MD5:signOrigStr];
    NSLog(@"下单签名 singOrigStr = %@", signMac);
    NSString *str = [NSString stringWithFormat:@"MERCHANTID=%@&SUBMERCHANTID=%@&ORDERSEQ=%@&ORDERAMT=%@&ORDERREQTRANSEQ=%@&ORDERREQTIME=%@&MAC=%@&TRANSCODE=%@",
                     MERID,
                     @"",
                     orderSeq,
                     [NSString stringWithFormat:@"%.0f",[amount floatValue]*100.0f],
                     orderReqTrnSeq,
                     orderTime,
                     signMac,
                     @"01"];
    
    _params = [[NSMutableDictionary alloc] init];
    
    [_params setObject:orderSeq             forKey:@"ORDERSEQ"];
    [_params setObject:orderReqTrnSeq       forKey:@"ORDERREQTRNSEQ"];
    [_params setObject:orderTime            forKey:@"ORDERREQTIME"];
    
    NSLog(@"下单接口信息：%@",str);
    
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    _connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
}

//获取当前时间戳
- (NSString *)getOrderTrSeq{
    NSDate *senddate=[NSDate date];
    NSString *locationString = [NSString stringWithFormat:@"%ld", (long)[senddate timeIntervalSince1970]];
    return locationString;
}

//获取当前时间毫秒级
- (NSString *)getOrderTimeMS{
    NSDate *senddate = [NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMddHHmmssSS"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    return locationString;
}

//获取当前时间分钟级
- (NSString *)getOrderTime{
    NSDate *senddate = [NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    return locationString;
}


- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        [[challenge sender] useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
        [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //self.receiveData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.receiveData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *receiveStr = [[NSString alloc]initWithData:self.receiveData encoding:NSUTF8StringEncoding];
    if([[receiveStr substringToIndex:2] isEqualToString:@"00"])
    {
        [self doOrder];
    }
    else
    {
        NSLog(@"下单失败：%@", receiveStr);
        
        [self showAlert:@"下单失败，请稍后再试！"];
    }
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"请求失败%@",[error localizedDescription]);
    [self showAlert:@"请求失败，请稍后再试！"];
}

- (void)showAlert:(NSString *)msg
{
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:nil message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    [alter show];
}

//订单处理
- (void)doOrder{
    
    //获取订单信息
    NSString *orderStr = [self orderInfos];
    [utils doBestPay:orderStr rootView:self];
    
}

#pragma mark -
#pragma mark  Private Methods
- (NSString *)orderInfos{
    
    NSMutableString * orderDes = [NSMutableString string];
    
    // 7个基本参数
    //1. 接口名称
    NSString *service = @"mobile.security.pay";
    [orderDes appendFormat:@"SERVICE=%@", service];
    //2. 商户号
    [orderDes appendFormat:@"&MERCHANTID=%@", MERID];
    //3. 商户密码 由翼支付网关平台统一分配给各接入商户
    [orderDes appendFormat:@"&MERCHANTPWD=%@", PSWD];
    //4. 子商户号
    [orderDes appendFormat:@"&SUBMERCHANTID=%@", @""];
    //5. 支付结果通知地址 翼支付网关平台将支付结果通知到该地址，详见支付结果通知接口
    [orderDes appendFormat:@"&BACKMERCHANTURL=%@", @"http://127.0.0.1:8040/wapBgNotice.action=yzf"];
    //6. 签名方式
    [orderDes appendFormat:@"&SIGNTYPE=%@", @"MD5"];
    //7. MAC验证信息 采用MD5加密
    NSString *encodeOrderStr = [NSString stringWithFormat:@"MERCHANTID=%@&ORDERSEQ=%@&ORDERREQTRNSEQ=%@&ORDERTIME=%@&KEY=%@", MERID, [_params objectForKey:@"ORDERSEQ"], [_params objectForKey:@"ORDERREQTRNSEQ"] , [_params objectForKey:@"ORDERREQTIME"] , KEYSTR];
    NSString *signStr = [MD5 MD5:encodeOrderStr];
    NSLog(@"加密原串%@-----加密串%@",encodeOrderStr,signStr);
    [orderDes appendFormat:@"&MAC=%@", signStr];
    
    // 16个业务参数
    //1. 订单号
    [orderDes appendFormat:@"&ORDERSEQ=%@", [_params objectForKey:@"ORDERSEQ"]];
    //2. 订单请求流水号，唯一
    [orderDes appendFormat:@"&ORDERREQTRNSEQ=%@", [_params objectForKey:@"ORDERREQTRNSEQ"]];
    //3. 订单请求时间 格式：yyyyMMddHHmmss
    [orderDes appendFormat:@"&ORDERTIME=%@", [_params objectForKey:@"ORDERREQTIME"]];
    //4. 订单有效截至日期
    [orderDes appendFormat:@"&ORDERVALIDITYTIME=%@", @""];
    //5. 订单金额/积分扣减
    [orderDes appendFormat:@"&ORDERAMOUNT=%@", @"0.01"];
    //6. 币种, 默认RMB
    [orderDes appendFormat:@"&CURTYPE=%@", @"RMB"];
    //7. 业务标识 optional
    [orderDes appendFormat:@"&PRODUCTID=%@", @"04"];
    //8. 产品描述 optional
    [orderDes appendFormat:@"&PRODUCTDESC=%@", @"联想手机"];
    //9. 产品金额
    [orderDes appendFormat:@"&PRODUCTAMOUNT=%@", @"0.01"];
    //10. 附加金额 单位元，小数点后2位
    [orderDes appendFormat:@"&ATTACHAMOUNT=%@",@"0.00"];
    //11. 附加信息 optional
    [orderDes appendFormat:@"&ATTACH=%@", @"88888"];
    //12. 分账描述 optional
    [orderDes appendFormat:@"&DIVDETAILS=%@", @"01320108043365000"];
    //13. 翼支付账户号
    [orderDes appendFormat:@"&ACCOUNTID=%@", @""];
    //14. 客户标识 在商户系统的登录名 optional
    [orderDes appendFormat:@"&CUSTOMERID=%@", @"gehudedengluzhanghao"];
    //15. 用户IP 主要作为风控参数 optional
    [orderDes appendFormat:@"&USERIP=%@", @"228.112.116.118"];
    //16. 业务类型标识
    [orderDes appendFormat:@"&BUSITYPE=%@", @"04"];
    return orderDes;
    
}


@end